package no.ntnu.idi.deid.patternmatching.search.dictionary.medicalcodes;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;

import no.ntnu.idi.deid.config.FilePaths;
import no.ntnu.idi.deid.documentunits.Token;
import no.ntnu.idi.deid.searchresultunits.CategoryTag;
import no.ntnu.idi.deid.searchresultunits.Tag;

/*
 * 
 *  ***************************SNOMED****************************
 * 
 */

public class Snomed_Elements {
	
	private static Map<String, String> snomedElements;
	
	private Snomed_Elements() {
		if (snomedElements == null){
			try {
				makeSnomedElementsSet();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static CategoryTag searchInSnomedElements(Token token) {
		new Snomed_Elements();
		String str = token.getStripped();
		String se = snomedElements.get(str);
		if(se!=null){
			CategoryTag tag = new CategoryTag(Tag.SNOMED);
			tag.setValues(str, se);
			return tag;
		}
		return null;
	}
	
	private void makeSnomedElementsSet() throws FileNotFoundException {
		snomedElements = new HashMap<String, String>();
		Scanner sc = new Scanner(new File(FilePaths.getSnomedInputPath()));
		while (sc.hasNextLine()) {
			String line = sc.nextLine();
			if(!line.contains("$$$$")){readAndHandleLine(line.trim());}
		}
		sc.close();
	}
	
	private void readAndHandleLine(String line){
		String code = line.split(" ")[0];
		String desc = line.substring(line.indexOf(" "));
		snomedElements.put(code.trim(), desc.trim());
	}
	
	public static CategoryTag searchDescriptionWithoutUNS(String str) {
		new Snomed_Elements();
		Iterator<Entry<String, String>> it = snomedElements.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			String fixedString = entry.getValue().replaceAll("UNS", "");
			fixedString = fixedString.replaceAll("\"","").trim();
			if(fixedString.equals(str.trim())){
				CategoryTag tag = new CategoryTag(Tag.SNOMED);
				tag.setValues(entry.getKey(), entry.getValue());
				return tag;
			}
		}
		return null;
	}	
}
